#include <qdir.h>

#include <mythtv/mythcontext.h>
#include <mythtv/uitypes.h>

#include "globals.h"
#include "programmeutils.h"
#include "metadata.h"
#include "metadatalistmanager.h"

namespace
{
    const int WATCHED_WATERMARK = 10000; // Less than this and the chain of
                                         // programmes will not be followed when
                                         // playing.
    const QString PROGRAMME_COVERFILE_DEFAULT_OLD = QObject::tr("None");
}

void PlayProgramme(const QString &filename, const MetadataListManager &programme_list)
{
    MetadataListManager::MetadataPtr item = programme_list.byFilename(filename);

    if (!item) return;

    QTime playing_time;

    do
    {
      playing_time.start();

      QString internal_mrl;
      QString handler = Metadata::getPlayer(item.get(), internal_mrl);
//       VERBOSE(VB_IMPORTANT, QString("Handler identified as %1").arg(handler));

      // No internal handler for this, play external
      QString command = Metadata::getPlayCommand(item.get());
//       VERBOSE(VB_IMPORTANT, QString("Executing %1").arg(command));

      if (command.length())
      {
          gContext->sendPlaybackStart();
          myth_system(command);
          gContext->sendPlaybackEnd();
      }

      break;
    }
    while (item && playing_time.elapsed() > WATCHED_WATERMARK);
}

void checkedSetText(LayerSet *container, const QString &item_name,
                           const QString &text)
{
    if (container)
    {
        UITextType *utt = dynamic_cast<UITextType *>
                (container->GetType(item_name));
        if (utt)
            utt->SetText(text);
    }
}

QStringList GetProgrammeDirs()
{
    QStringList tmp = QStringList::split(":",DEFAULT_PROGRAMMESTARTUP_DIR);
//             gContext->GetSetting("mythiplayer.RootDir", DEFAULT_PROGRAMMESTARTUP_DIR));
    for (QStringList::iterator p = tmp.begin(); p != tmp.end(); ++p)
    {
        *p = QDir::cleanDirPath(*p);
    }
    return tmp;
}

QString getDisplayYear(int year)
{
    return year == PROGRAMME_YEAR_DEFAULT ? "?" : QString::number(year);
}

QString getDisplayRating(const QString &rating)
{
    if (rating == "<NULL>")
        return QObject::tr("No rating available.");
    return rating;
}

QString getDisplayUserRating(float userrating)
{
    return QString::number(userrating, 'f', 1);
}

QString getDisplayLength(int length)
{
    return QString::number(length) + " " + QObject::tr("minutes");
}

bool isDefaultCoverFile(const QString &coverfile)
{
    return coverfile == PROGRAMME_COVERFILE_DEFAULT ||
            coverfile == PROGRAMME_COVERFILE_DEFAULT_OLD;
}

